import java.util.HashMap;

import se.sics.jasper.SICStus;
import se.sics.jasper.SPTerm;

public class PrologQuestionneur {
	private SPTerm plateau;
	private boolean isPremier;
	private SICStus sicstus;
	private HashMap<String, SPTerm> map;

	public PrologQuestionneur() {
		this.plateau = null;
		this.sicstus = null;
		this.isPremier = false;
		this.map = new HashMap<String, SPTerm>();
	}

	public boolean init(Couleur couleur, String fichierPL) {
		boolean result = true;
		try {
			this.sicstus = new SICStus();
			this.sicstus.load(fichierPL);
			String joueur = "j";
			if (couleur == Couleur.BLEU) {
				joueur = "a";
			}			
			this.sicstus.query("initPlateau(" + joueur
					+ ", P).", this.map);
			this.plateau = this.map.get("P");
		} catch (Exception e) {
			e.printStackTrace(System.err);
			result = false;
		} finally {
			this.map.clear();
		}
		return result;
	}

	public void setJoueurPremier() {
		this.isPremier = true;
	}

	public boolean isPremier() {
		return this.isPremier;
	}

	public SPTerm getPlateau() {
		return this.plateau;
	}

	public void joueCoup(Coordonnee depart, Coordonnee arrivee) {
		try {
			depart = depart.coordJavaToProlog();
			arrivee = arrivee.coordJavaToProlog();
			this.sicstus.query("applique_coup_java([" + depart.x + ","
					+ depart.y + "],[" + arrivee.x + "," + arrivee.y + "],"
					+ this.plateau + ", P).", this.map);
			this.plateau = this.map.get("P");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			this.map.clear();
		}
	}

	public Coup genereCoup() {
		try {
			System.out.println("Appel prolog");
			this.sicstus.query("run(" + this.plateau + ", D, A, P, T, B).",
					this.map);
			this.plateau = this.map.get("P");
			SPTerm[] depTerm = this.map.get("D").toTermArray();
			int dx = Integer.parseInt(depTerm[0].toString());
			int dy = Integer.parseInt(depTerm[1].toString());
			Coordonnee depart = new Coordonnee(dx, dy);
			depart = depart.coordPrologToJava();
			
			SPTerm[] arrTerm = this.map.get("A").toTermArray();
			int ax = Integer.parseInt(arrTerm[0].toString());
			int ay = Integer.parseInt(arrTerm[1].toString());
			Coordonnee arrivee = new Coordonnee(ax, ay);
			arrivee = arrivee.coordPrologToJava();
			
			int type = (int) this.map.get("T").getInteger();
			int bloque = (int) this.map.get("B").getInteger();
			
			System.out.println("Fin appel prolog");
			return new Coup(type, bloque, depart, arrivee);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			this.map.clear();
		}
		return null;
	}



}
